<template>
  <el-dialog
    v-if="dialogVisible"
    :title="`${formData.id ? '编辑' : '创建'}权限组`"
    :visible.sync="dialogVisible"
    @close="close"
  >
    <el-form
      ref="form"
      :model="formData"
      :rules="formRules"
      label-width="260px"
    >
      <el-form-item label="用户名" prop="title">
        <el-input v-model="formData.title" style="width: 300px" />
      </el-form-item>
      <el-form-item label="权限分配">
        <el-tree
          ref="tree"
          :data="list"
          :props="defaultProps"
          node-key="id"
          default-expand-all
          show-checkbox
          :default-checked-keys="checkList"
          check-strictly
        />
      </el-form-item>
    </el-form>
    <div slot="footer">
      <el-button @click="dialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="btnOk">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { getMenus } from '@/api/menus'
import {
  addPermissions,
  permissions,
  editPermissions
} from '@/api/permissions'
export default {
  data() {
    return {
      dialogVisible: false,
      formData: {},
      formRules: {
        title: [{ required: true, trigger: 'blur', message: '不能为空' }]
      },
      list: [],
      defaultProps: { label: 'title', children: 'childs' },
      menuList: [],
      checkList: []
    }
  },
  created() {
    this.getMenus()
  },
  methods: {
    close() {
      this.$refs.form.clearValidate()
      this.formData = {}
      this.checkList = []
    },
    async btnOk() {
      this.checkList = this.$refs.tree.getCheckedKeys()
      await this.$refs.form.validate()
      if (this.formData.id) {
        await editPermissions({
          ...this.formData,
          permissions: this.checkList
        })
        window.location.reload()
      } else {
        await addPermissions({ ...this.formData, permissions: this.checkList })
      }
      this.$message.success('操作成功')
      this.$emit('update')
      this.dialogVisible = false
    },
    async getPermissions(id) {
      const res = await permissions(id)
      this.formData = res
      this.checkList = res.permissions
    },
    async getMenus() {
      const res = await getMenus()
      res.map((item) => {
        item.childs.map((val) => {
          if (!val.points) return
          val.childs = val.points
        })
      })
      console.log(res)
      this.list = res
    }
  }
}
</script>

<style>
</style>
